import axios from 'axios';
import router from '@/common/router';
import {SERVER_URL} from '@/common/const';
import { rejects } from 'assert';

// 环境的切换
if(process.env.NODE_ENV == 'development'){
    axios.defaults.baseURL=SERVER_URL;
}
else{
    axios.defaults.baseURL=SERVER_URL;
}

// 超时时间
axios.defaults.timeout=1000;
axios.defaults.withCredentials=true;

// 响应拦截
axios.interceptors.response.use(
    response => {
        if (response.status == 200){
            return Promise.resolve(response);
        } else{
            return Promise.reject(response);
        }
    },
    error =>{
        if(error.response.status){
            switch(error.response.status){
                case 401:  //未授权
                router.replace({
                    path:'/login',
                    query:{
                        redirect:router.currentRoute.fullPath
                    }
                });
                break;

                case 404:
                break;

                default:
      
            }
            return Promise.reject(error.response);
        }
    }
);


// export function get(url, params) {
//     var pro= new Promise((resolve, reject) => {
//       axios
//         .get(url, {
//           params: params
//         })
//         .then(res => {
//           resolve(res.data);
//         })
//         .catch(err => {
//           reject(err.data);
//         });
//     });
//     return pro;
// }

export function get(url, params) {
    return new Promise((resolve, reject) => {
      axios
        .get(url, {
          params: params
        })
        .then(res => {
          resolve(res.data);
        })
        .catch(err => {
          reject(err.data);
        });
    });
}

export function post(url,params){
    return new Promise((resolve,reject) => {
        axios
            .post(url,params)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data);
            });
    });
}

export function put(url,params){
    return new Promise((resolve,reject) => {
        axios
            .put(url,params)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data);
            });
    });
}

export function del(url,params){
    return new Promise((resolve,reject) => {
        axios
            .delete(url,params)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data);
            });
    });
}






